package com.xsp.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Proxy;

/**
 * @author xsp
 * @date 2024/1/20
 * @desc 动态代理
 */
public class ProxyFactory {
    public ProxyFactory(Object target) {
        this.target = target;
    }

    private Object target;

    private final Logger logger = LoggerFactory.getLogger(ProxyFactory.class);

    public Object getProxyInstance() {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                (proxy, method, args) -> {
                    logger.debug("代理对象开始工作");
                    try {
                        // 执行目标对象的方法
                        return method.invoke(target, args);
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("执行新增图书信息时发生了异常：{}", e.getMessage());
                        logger.error("发生异常时，新增的图书信息是：{}", args.toString());
                        throw e;
                    }
                });
    }
}
